<html>
<head>
<title>Friend Feed</title>

<!-- Yahoo UI-->
<!-- Sam Skin CSS -->
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.1/build/container/assets/skins/sam/container.css">

<!-- Dependencies -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/yahoo-dom-event/yahoo-dom-event.js"></script>

<!-- Source file -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/container/container-min.js"></script>

<!-- Sam Skin CSS -->
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.1/build/container/assets/skins/sam/container.css">

<!-- Dependencies -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/yahoo-dom-event/yahoo-dom-event.js"></script>

<!-- Source file -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/container/container-min.js"></script>

<div id="myDialog" style='visibility: hidden;'>
<div class="hd"></div>  
  <div class="bd">
    <form method="POST">
      <table style="border-collapse: collapse; border-spacing: 0; padding: 0; margin: 0; font-family: Arial, sans-serif; border: 4px solid #6797d3; color: #222222">
        <tr>
          <td style="background-color: #ecf2fa; padding: 3px; padding-left: 5px; padding-top: 5px; border: 0; border-bottom: 1px solid #6797d3"><a href="http://friendfeed.com/" target="_blank"><img src="http://friendfeed.com/static/images/logo-api.png" width="160" height="34" alt="FriendFeed" style="padding:0; border:0; margin:0"/></a></td>
          <td style="background-color: #ecf2fa; padding: 3px; padding-right: 20px; border: 0; border-bottom: 1px solid #6797d3; text-align: right; vertical-align: middle; font-size: 16pt; font-weight: bold; color: gray">Setting</td>
        </tr>
        <tr>
          <td style="background-color: white; padding: 15px; border: 0" colspan="2">
            <table style="border-collapse: collapse; border-spacing: 0; border: 0; padding: 0; margin: 0">
              <tr>
                <td style="border: 0; padding: 5px; font-size: 10pt">FriendFeed nickname or email:</td>
                <td style="border: 0; padding: 5px; font-size: 10pt"><input type="text" id="friendfeed_nickname" name="friendfeed_nickname" style="width: 10em"/></td>
              </tr>
              <tr>
                <td style="border: 0; padding: 5px; font-size: 10pt">Remote key [ <a href="http://friendfeed.com/remotekey" style="color: #1030cc" target="_blank">find your key</a> ]:</td>
                <td style="border: 0; padding: 5px; font-size: 10pt"><input type="password" id="friendfeed_remote_key" name="friendfeed_remote_key" style="width: 10em"/></td>
              </tr>
              <tr>
                <td align='right'>
                <input type="button" id="submit" name="save" value="Save" onclick="handleSubmit(this)" />
                <input type="button" id="cancel" name="cancel" value="Cancel" onclick="handleCancel(this)" />
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
    </form>
  </div>
</div>

<script type="text/javascript">
var isDebug = true; // for debug locally
//var isDebug = false;

var handleCancel = function() {
  myDialog.cancel();
}
var handleSubmit = function() {
  if (myDialog.getData().friendfeed_nickname == '') {
    alert("please input a valid nickname!");
    return false;
  }  
  saveUserSetting(myDialog.getData().friendfeed_nickname, myDialog.getData().friendfeed_remote_key);
  myDialog.hide();
  showUserFeed();
}

var myDialog;
function initDialog() {
  myDialog = new YAHOO.widget.Dialog("myDialog", { width : "30em",
							  fixedcenter : false,
							  visible : false, 
                modal : true,
							  constraintoviewport : true
							});
}

function showUserDialog() {
  myDialog.render();
  myDialog.show();
}
</script>

<script type="text/javascript" src="http://friendfeedos.googlecode.com/svn/trunk/lib/dateutils.js"></script>
<script type="text/javascript">  
	function onGetUserFeed(obj) {
      if (!obj.data) {
        msgFetchDataFailed();
        return;
      }
      
	    var html = "<b> " + getUsername() + "'s FriendFeed</b>";
	    //html += "<ul>";
      with (obj.data) {
	        now = new Date();        
	        for (i in entries) {
            var str = "";
            try {
              str += "<div style='margin: 2px;'>";
              str += "<img src='" + entries[i].service.iconUrl + "' /> ";
              str += "<a href='" + entries[i].user.profileUrl + "'>" + entries[i].user.name + "</a> ";
              str += "on <a href='" + entries[i].service.profileUrl + "'>" + entries[i].service.name + "</a> ";
              str += "<div id='entries'><a href='" + entries[i].link + "'>" + entries[i].title + "</a>";
              str += " published " +  Date.getDateIntervalDesc(now, Date.parseISO8601(entries[i].published));
              str += "</div>";
              str += "</div>";
              html += str;
            }
            catch (e) {
            }
	        }
	     }
       //html  += "</ul>";
       
       document.getElementById("feeds").innerHTML = html;
       gadgets.window.adjustHeight();
  	}
    
    function showUserFeed(){     
      if (!isDebug) {
  	    var params = {};
  		  params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
  	    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
        var username = getUsername();
        if (username == null) {          
          msgBindAccoutFirst();
          return;
        }
  	    var url = getFeedApiUrl() + username;
        try {
  	      gadgets.io.makeRequest(url, onGetUserFeed, params);
        }
        catch(e) {
          msgFetchDataFailed();
          return;
        }
      }
      else {        
        var username = getUsername();
        if (username == null) {          
          return;
        }
        var url = getFeedApiUrl() + username;
        
        var client = new createXMLHttpRequest( function() {
          var obj = new Object();
          try {
            obj.data = eval('(' + client.responseText + ')');
          }
          catch(e) {
            msgFetchDataFailed();
            return;
          }         
          
          onGetUserFeed(obj);
        } );
        
        client.open("GET", url, false);       
        client.send(null);
      }
    }      


	var FF_NICKNAME = "ff_nickname", FF_REMOTEKEY = "ff_remotekey";
  var nickname, remotekey;
  var signal = new Object();
    
  function handleRequestGetSetting(data) {
    if (data.hadError()) {
      //Handle error using viewer.getError()...
      nickname = null;
      remotekey = null;
    }
    else {           
      var owner = data.get("owner").getData();
      var ownerData = data.get("ownerData").getData()[owner.getId()];
      nickname = ownerData[FF_NICKNAME];
      remotekey = ownerData[FF_REMOTEKEY];      
    }

    showUserFeed();
  }

	function getStoredUsername() { 
    if (isDebug) return;
    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest('OWNER'), 'owner');
    req.add(req.newFetchPersonAppDataRequest('OWNER', [FF_NICKNAME, FF_REMOTEKEY]), 'ownerData');
    req.send(handleRequestGetSetting);   
  }
  
  function getStoredRemoteKey() {
    return remotekey;
  }
  
  function saveUserSetting(name, key) {
    nickname = name;
    remotekey = key;
    if (isDebug) return;
    var req = opensocial.newDataRequest();
    req.add(req.newUpdatePersonAppDataRequest('OWNER', FF_NICKNAME, name));
    req.add(req.newUpdatePersonAppDataRequest('OWNER', FF_REMOTEKEY, key));    
    req.send(afterSave);
  }
  
  function afterSave(data) {
    // check if save successfully
    if (data.hadError()) {
      msg('sorry, saving user setting failed!');
    }
  }
  
  function loadUserSetting() {  
    getStoredUsername();
  }
  
	function getUsername() {
    if (nickname === undefined)
      return null;
    else
      return nickname;
	}
	
	function getFeedApiUrl() {
		return "http://friendfeed.com/api/feed/user/";
	}    
  
  // show message 
  function msgFetchDataFailed() {
    log(username + ' does not exist in FriendFeed');
  }
  
  function msgBindAccoutFirst() {
    document.getElementById("feeds").innerHTML = 'please bind to your friendfeed account!';
  }
  
  // create XMLHttpRequest object
  var xhr;
  function createXMLHttpRequest(func) {
    try { xhr = new XMLHttpRequest(); } catch(e) {
      try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
        try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {
           log("XMLHttpRequest not supported");
           return null;
        }
      }  
    }  
   
    xhr.onreadystatechange =  function() { if (xhr.readyState == 4) func(); }
    return xhr;
  } 
 
  function log(msg) {
    LOG = document.getElementById('log');
    LOG.innerHTML += msg + '<br>';
  }
  
  function msg(info) {
    alert(info);
  }

  function waitForObject(signalName, timeout) {
    log('wait ' + signal[signalName]);
    while(signal[signalName] == false) ;
  }
  
  function init() {   
    initDialog();
    loadUserSetting();    
  }
</script>
</head>

<body onload='init()'>
  <div id='title' style='margin: 4px;'><table><tr><td><b><a href='http://friendfeed.com'>FriendFeed</a></b></td><td align='right'><a href='javascript:showUserDialog();'>Setting</a></td></tr></table></div>
  <div id='feeds'></div>
	<div id='log'></div>
</body>
</html>